package no.la58.scribbles.client.uicomponents;

import no.la58.scribbles.client.ClientFactory;
import no.la58.scribbles.client.event.LoggedInEvent;
import no.la58.scribbles.shared.LoggedInResponse;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class LoginView extends Composite implements LoggedInEvent.LoginHandler {

    private static LoginViewUiBinder uiBinder = GWT.create(LoginViewUiBinder.class);

    interface LoginViewUiBinder extends UiBinder<Widget, LoginView> {
    }

    private static ClientFactory clientFactory = GWT.create(ClientFactory.class);

    @UiField
    Anchor loginlink;

    public LoginView() {
	initWidget(uiBinder.createAndBindUi(this));
	LoggedInEvent.register(clientFactory.getEventBus(), this);
    }

    @Override
    public void onLoginResult(LoggedInResponse response) {
	updateLoginLink(response);
    }

    private void updateLoginLink(LoggedInResponse response) {
	String hrefText = "";
	String toolTip = "";
	if (response.isLoggedIn()) {
	    hrefText = "Log out";
	    toolTip = "Logged in as " + response.getUsermail();
	} else {
	    hrefText = "Log in";
	    toolTip = "Log in with your google-account!";
	}
	loginlink.setHref(response.getLogInOutUrl());
	loginlink.setTitle(toolTip);
	loginlink.setText(hrefText);
    }

}
